package cn.itcast.web.controller.cargo;

import cn.itcast.domain.cargo.Export;
import cn.itcast.domain.cargo.ExportProduct;
import cn.itcast.domain.cargo.ExportProductExample;
import cn.itcast.domain.system.User;
import cn.itcast.service.cargo.ExportProductService;
import cn.itcast.service.cargo.ExportService;
import cn.itcast.web.controller.BaseController;
import cn.itcast.web.utils.BeanMapUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.sql.DataSource;
import java.io.InputStream;
import java.util.*;

/**
 * 导入报运单PDF
 */
@Controller
@RequestMapping("/cargo/export")
public class PdfController extends BaseController{

    /**
     * 1） 简单导入
     */
    @RequestMapping("/exportPdf2")
    public void exportPdf2() throws Exception {
        //1.读取.jasper模板文件
        InputStream inputStream = session.getServletContext().getResourceAsStream("/jasper/test01.jasper");

        //2.填充数据
        /**
         * 参数一：输入流
         * 参数二：Map参数
         * 参数三：数据源参数
         */
        JasperPrint print = JasperFillManager.fillReport(inputStream, new HashMap<>(), new JREmptyDataSource());

        //3.导出PDF
        /**
         * 参数一：JasperPrint对象
         * 参数二：输出流（硬盘或浏览器）
         */
        JasperExportManager.exportReportToPdfStream(print,response.getOutputStream());
    }

    /**
     * 2) Map参数导出
     * @throws Exception
     */
    @RequestMapping("/exportPdf3")
    public void exportPdf3() throws Exception {
        //1.读取.jasper模板文件
        InputStream inputStream = session.getServletContext().getResourceAsStream("/jasper/test02_map.jasper");

        //2.填充数据
        /**
         * 参数一：输入流
         * 参数二：Map参数
         * 参数三：数据源参数
         */
        //填充Map参数
        Map map = new HashMap<>();
        map.put("userName","小苍");
        map.put("email","xc@qq.com");
        map.put("companyName","苍谷科技");
        map.put("deptName","视频组");


        JasperPrint print = JasperFillManager.fillReport(inputStream, map, new JREmptyDataSource());

        //3.导出PDF
        /**
         * 参数一：JasperPrint对象
         * 参数二：输出流（硬盘或浏览器）
         */
        JasperExportManager.exportReportToPdfStream(print,response.getOutputStream());
    }

    //注入数据源
    @Autowired
    private DataSource dataSource;



    /**
     * 3）JDBC连接方式的数据源填充
     * @throws Exception
     */
    @RequestMapping("/exportPdf4")
    public void exportPdf4() throws Exception {
        //1.读取.jasper模板文件
        InputStream inputStream = session.getServletContext().getResourceAsStream("/jasper/test03_jdbc.jasper");

        //2.填充数据

        //注意：如果Jdbc连接方式，必须设置Connection连接对象

        JasperPrint print = JasperFillManager.fillReport(inputStream, new HashMap<>(),dataSource.getConnection());

        //3.导出PDF
        /**
         * 参数一：JasperPrint对象
         * 参数二：输出流（硬盘或浏览器）
         */
        JasperExportManager.exportReportToPdfStream(print,response.getOutputStream());
    }

    /**
     * 4）JavaBea方式数据源填充数据
     * @throws Exception
     */
    @RequestMapping("/exportPdf5")
    public void exportPdf5() throws Exception {
        //1.读取.jasper模板文件
        InputStream inputStream = session.getServletContext().getResourceAsStream("/jasper/test04_javabean.jasper");

        //2.填充数据

        //定义List集合，List集合包含JavaBean
        List<User> list = new ArrayList<>();

        for(int i=1;i<=10;i++) {
            User user = new User();
            user.setUserName("小泽-"+i);
            user.setEmail("xz"+i+"@qq.com");
            user.setCompanyName("小科技泽-"+i);
            user.setDeptName("视频"+i+"组");
            list.add(user);
        }

        JasperPrint print = JasperFillManager.fillReport(inputStream, new HashMap<>(),new JRBeanCollectionDataSource(list));

        //3.导出PDF
        /**
         * 参数一：JasperPrint对象
         * 参数二：输出流（硬盘或浏览器）
         */
        JasperExportManager.exportReportToPdfStream(print,response.getOutputStream());
    }

    /**
     * 5）图形报表导出
     * @throws Exception
     */
    @RequestMapping("/exportPdf6")
    public void exportPdf6() throws Exception {
        //1.读取.jasper模板文件
        InputStream inputStream = session.getServletContext().getResourceAsStream("/jasper/test05_charts.jasper");

        //2.填充数据

        //定义List集合，List集合包含JavaBean
        List<Map<String,Object>> list = new ArrayList<>();

        for(int i=1;i<=5;i++) {

            Map map = new HashMap();
            map.put("name","工厂"+i);
            map.put("value",new Random().nextInt(100));

            list.add(map);
        }

        JasperPrint print = JasperFillManager.fillReport(inputStream, new HashMap<>(),new JRBeanCollectionDataSource(list));

        //3.导出PDF
        /**
         * 参数一：JasperPrint对象
         * 参数二：输出流（硬盘或浏览器）
         */
        JasperExportManager.exportReportToPdfStream(print,response.getOutputStream());
    }


    @Reference
    private ExportService exportService;
    @Reference
    private ExportProductService exportProductService;

    /**
     * 报运单导出PDF
     * @throws Exception
     */
    @RequestMapping("/exportPdf")
    @ResponseBody  //注意：如果方法返回为void，@ResponseBody会close和flush掉response输出流
    public void exportPdf(String id) throws Exception {
        //1.读取.jasper模板文件
        InputStream inputStream = session.getServletContext().getResourceAsStream("/jasper/export.jasper");

        //2.查询报运单数据
        Export export = exportService.findById(id);

        //3.查询报运商品数据
        ExportProductExample exportProductExample = new ExportProductExample();
        ExportProductExample.Criteria exportProductExampleCriteria = exportProductExample.createCriteria();

        //export_id = 'xxx'
        exportProductExampleCriteria.andExportIdEqualTo(id);

        List<ExportProduct> exportProductList = exportProductService.findAll(exportProductExample);


        //4.把Export对象的内容转换为Map集合
        Map map = BeanMapUtils.beanToMap(export);


        JasperPrint print = JasperFillManager.fillReport(inputStream, map ,new JRBeanCollectionDataSource(exportProductList));

        //3.导出PDF
        /**
         * 参数一：JasperPrint对象
         * 参数二：输出流（硬盘或浏览器）
         */
        //设置响应头（给浏览器提示框）
        response.setHeader("Content-Disposition","attachment;filename=export.pdf");
        JasperExportManager.exportReportToPdfStream(print,response.getOutputStream());
    }
}
